<template>
  <div>
    <div class="register-container">
      <!-- 注册内容 -->
      <div class="register">
        <h3>
          注册新用户
          <span class="go"
            >我有账号，去 <router-link to="/login" >登录</router-link>
          </span>
        </h3>
        <!-- validation-schema属性值为包含校验规则函数的对象名。
             通过作用域插槽，<Form>可通过解构拿到errors对象给子节点使用。
             errors.username即为校验函数中我们返回的错误文本消息，
             可通过v-if动态提示消息。
        -->
        <Form
          class="content-list"
          :validation-schema="schema"
          ref="formRef"
          @submit="onSubmit"
          v-slot="{ setFieldError }"
        >
          <div class="content">
            <label>手机号:</label>
            <Field
              v-model="userForm.phone"
              name="phoneFn"
              placeholder="请输入你的手机号"
            />
            <ErrorMessage class="error-msg" name="phoneFn"></ErrorMessage>
          </div>
          <div class="content">
            <label>验证码:</label>
            <Field
              v-model="userForm.code"
              name="codeFn"
              type="text"
              placeholder="请输入验证码"
            />
            <button
              class="getcode"
              @click.prevent="getCode(setFieldError)"
              :disabled="codeDtnDisabled"
            >
              {{
                userForm.time <= 60
                  ? userForm.time + "秒后重新发送"
                  : userForm.isSendCode
                  ? "重新获取验证码"
                  : "获取短信验证码"
              }}
            </button>
            <!-- <h1 class="getcode" @click="getCode(setFieldError, setErrors)">
              获取验证码
            </h1> -->
            <ErrorMessage class="error-msg" name="codeFn"></ErrorMessage>
          </div>
          <div class="content">
            <label>登录密码:</label>
            <Field
              v-model="userForm.password"
              name="passwordFn"
              type="text"
              placeholder="请输入你的登录密码"
            />
            <ErrorMessage class="error-msg" name="passwordFn"></ErrorMessage>
          </div>
          <div class="content">
            <label>确认密码:</label>
            <Field
              v-model="userForm.rePassword"
              name="rePasswordFn"
              type="text"
              placeholder="请输入确认密码"
            />
            <ErrorMessage class="error-msg" name="rePasswordFn" />
          </div>
          <div class="controls">
            <Field name="reIsAgree" type="checkbox" v-model="userForm.isAgree">
            </Field>
            <!-- v-model="userForm.isAgree" -->
            <span>同意协议并注册《天猫用户协议》</span>
            <ErrorMessage name="reIsAgree" class="error-msg" />
          </div>
          <div class="btn">
            <button>完成注册</button>
          </div>
        </Form>
      </div>

      <!-- 底部 -->

      <div class="copyright">
        <ul>
          <li>关于我们</li>
          <li>联系我们</li>
          <li>联系客服</li>
          <li>商家入驻</li>
          <li>营销中心</li>
          <li>手机天猫</li>
          <li>销售联盟</li>
          <li>天猫社区</li>
        </ul>
        <div class="address">地址：北京市昌平区宏福科技园综合楼6层</div>
        <div class="beian">京ICP备19006430号</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "SRegister",
};
</script>

<script lang="ts" setup>
import { Form, Field, ErrorMessage } from "vee-validate";
import { reactive, ref, onMounted, onUnmounted, computed } from "vue";
import { reqGetRegisterCode, reqPostRegisterPass } from "@/api/register";
import { useRouter } from "vue-router";
import { phoneReg, codeReg, passwordReg } from "@/utils/rules";
const router = useRouter();
// 表单验证 <Form>用来替换原生<form>, <Field>用来替换原生<input>
// v-model为双向绑定的表单数据，name属性值schema对象中对应的校验函数名

const formRef = ref(null);

// 1. 定义表单数据
const userForm = reactive({
  phone: "",
  password: "",
  code: "",
  rePassword: "",
  isAgree: true,
  time: 61,
  isSendCode: false,
  isCode: "",
});

// 2. 定义表单效验规则

const schema = {
  phoneFn(value) {
    if (!value) return "手机号不能为空";
    if (!phoneReg.test(value)) return "请填写正确的手机号";
    return true;
  },
  // 参数value为需校验的表单值
  // 函数返回值为true时通过，为字符串时则为不通过时的提示消息。
  codeFn(value) {
    if (!value) return "验证码必填";
    if (!codeReg.test(value)) return "请填写正确的验证码";
    return true;
  },
  passwordFn(value) {
    if (!value) return "密码必填";
    if (!passwordReg.test(value)) return "请填写正确的密码";
    return true;
  },
  rePasswordFn(value) {
    if (!value) return "密码必填";
    if (!(value === userForm.password)) return "密码不一致请重新输入";
    return true;
  },
  reIsAgree(value) {
    if (!value) return true;
    return "请阅读并同意天猫用户协议";
  },
};
// 3. 获取验证码
const getCode = async (setFieldError) => {
  if (!phoneReg.test(userForm.phone)) {
    setFieldError("codeFn", "请输入手机号，在发送验证码");
    return;
  }
  sessionStorage.setItem("isSendCode", true);
  // 如果发送过验证码，要显示重新发送
  userForm.isSendCode = true;
  setinterval();
  const resCode = await reqGetRegisterCode(userForm.phone);
  userForm.isCode = resCode;
  // console.log(resCode);
};

let timeId = null;
const setinterval = () => {
  userForm.time--;
  timeId = setTimeout(() => {
    // 判断超过1s我就停止调用
    if (userForm.time <= 1) {
      userForm.time = 61;
      // 清空会话存储
      sessionStorage.setItem("isSendCode", false);
      return;
    }
    setinterval();
  }, 100);
};

// 4. 按钮禁用
const codeDtnDisabled = computed(
  () => !phoneReg.test(userForm.phone) || userForm.time <= 60
);

// 6. 表单提交跳转到指定位置
const onSubmit = async () => {
  // console.log("注册成功并跳转");
  const { phone, password, code } = userForm;
  await reqPostRegisterPass({ phone, password, code });
  //  跳转到登录页
  router.push("/login");
};
onMounted(() => {
  // 5. 页面加载初始化判断之前是否发送验证码短信
  const isSendCode = JSON.parse(sessionStorage.getItem("isSendCode"));
  /*  isSendCode返回的是字符串的false ，判断也是返回ture ，
          JSON.parse转化
       */
  if (isSendCode) {
    userForm.isSendCode = true;
    setinterval();
  }
});

onUnmounted(() => {
  clearTimeout(timeId);
});
</script>
<style lang="less" scoped>
.register-container {
  height: calc(100vh - 160px);

  .register {
    width: 1200px;
    height: 100%;
    min-height: 600px;
    border: 1px solid rgb(223, 223, 223);
    margin: 30px auto 0;

    h3 {
      background: #ececec;
      margin: 0;
      padding: 6px 15px;
      color: #333;
      border-bottom: 1px solid #dfdfdf;
      font-size: 20.04px;
      line-height: 30.06px;

      span {
        font-size: 14px;
        float: right;

        a {
          color: #e1251b;
        }
      }
    }

    div:nth-of-type(1) {
      margin-top: 40px;
    }

    .content {
      padding-left: 390px;
      margin-bottom: 50px;
      position: relative;

      label {
        font-size: 14px;
        width: 96px;
        text-align: right;
        display: inline-block;
      }

      input {
        width: 270px;
        height: 38px;
        padding-left: 8px;
        box-sizing: border-box;
        margin-left: 5px;
        outline: none;
        border: 1px solid #999;
      }

      img {
        vertical-align: sub;
      }

      .error-msg {
        position: absolute;
        top: 121%;
        left: 495px;
        color: red;
      }
    }

    .controls {
      text-align: center;
      position: relative;

      input {
        vertical-align: middle;
      }

      .error-msg {
        position: absolute;
        top: 100%;
        left: 495px;
        color: red;
      }
    }

    .btn {
      text-align: center;
      line-height: 36px;
      margin: 17px 0 0 55px;

      button {
        outline: none;
        width: 270px;
        height: 36px;
        background: #e1251b;
        color: #fff !important;
        display: inline-block;
        font-size: 16px;
      }
    }

    .getcode {
      height: 38px;
      margin-left: 10px;
      padding: 5px;
    }
  }

  .copyright {
    width: 1200px;
    margin: 0 auto;
    text-align: center;
    line-height: 24px;

    ul {
      li {
        display: inline-block;
        border-right: 1px solid #e4e4e4;
        padding: 0 20px;
        margin: 15px 0;
      }
    }
  }
}
</style>
